﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model.Object;
using Model.DataContext;
namespace Nongsan.Controllers
{
    public class HomeController : Controller
    {
        private DataContext db = new DataContext();
        public ActionResult Index()
        {

            HttpCookie cookie = Request.Cookies["test"];
            if (cookie == null)
            {
                cookie = new HttpCookie("test");
                cookie["count"] = 0 + "";
                cookie.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(cookie);
            }


            else
            {
                cookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(cookie);

            }

            //ctx.Banners.Add(new Banner { ID = 1,ImagePath="a", Title = "a", Link = "a",Order="a" });
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult Xemtintuc(int id)
        {
            var kq = (from n in db.TinTucs where n.ID == id select n).FirstOrDefault();
            ViewBag.tin = kq;
            return View();
        }

        public ActionResult XemChiTietSanPham(int id)
        {
            var kq = (from n in db.SanPhams where n.ID == id select n).FirstOrDefault();
            ViewBag.loai = (from n in db.LoaiSanPhams where n.ID == kq.ID_Loaisanpham select n).FirstOrDefault();
            ViewBag.sanpham = (from n in db.SanPhams where n.ID == id select n).FirstOrDefault();
            ViewBag.hinhanh = (from n in db.HinhAnhs where n.ID_SanPham == id select n).ToList<HinhAnh>();
            ViewBag.sanphamnext = (from n in db.SanPhams where n.ID > id && n.ID_Loaisanpham == kq.ID_Loaisanpham select n).FirstOrDefault();
            return View();
        }

        public ActionResult XemNhanhChiTietSanPham(int id)
        {
            ViewBag.sanpham = (from n in db.SanPhams where n.ID == id select n).FirstOrDefault();
            ViewBag.hinhanh = (from n in db.HinhAnhs where n.ID_SanPham == id select n).ToList<HinhAnh>();
            return View();
        }

        public ActionResult XemChiTietLoaiSanPham(int id)
        {
            ViewBag.loaisp = (from n in db.LoaiSanPhams where n.ID == id select n).FirstOrDefault();
            ViewBag.dssanpham = (from n in db.SanPhams where n.ID_Loaisanpham == id select n).ToList<SanPham>();
            return View();
        }

        public ActionResult getcountsp()
        {
            string s = "";
            HttpCookie cookie = Request.Cookies["test"];
            if (cookie == null)
            {
                cookie = new HttpCookie("test");
                cookie["count"] = 0 + "";
                cookie.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(cookie);
            }
            int x = Convert.ToInt32(cookie["count"]);
            s = "<span>Giỏ Hàng (" + (x + 1) + ")</span>";
            Response.Write(s);
            return null;
        }
        public ActionResult getcountsp_newsite()
        {
            string s = "";
            HttpCookie cookie = Request.Cookies["test"];
            if (cookie == null)
            {
                cookie = new HttpCookie("test");
                cookie["count"] = 0 + "";
                cookie.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(cookie);
            }
            int x = Convert.ToInt32(cookie["count"]);
            s = "<span>Giỏ Hàng (" + (x) + ")</span>";
            Response.Write(s);
            return null;
        }
        public ActionResult Getsanphammoithem_newsite()
        {

            HttpCookie cookie = Request.Cookies["test"];
            if (cookie == null)
            {
                cookie = new HttpCookie("test");
                cookie["count"] = 0 + "";
                cookie.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(cookie);
            }


            int dem = Convert.ToInt32(cookie["count"]);

            if (cookie["count"] != "0")
            {

                List<string> lst = new List<string>();
                for (int j = 0; j < dem + 1; j++)
                {
                    lst.Add(cookie[j + ""]);
                }

                string s = "";
                int tongtien = 0;
                s += "<div class='details-border'></div><p class='block-subtitle text-recently'>Sản phẩm mới thêm</p>";

                List<string> lstspmdn = dsspmoithemduynhat(lst);
                foreach (string spdn in lstspmdn)
                {
                    int soluong = 0;

                    foreach (string ss in lst)
                    {
                        if (ss == spdn)
                        {
                            soluong++;
                        }


                    }
                    int iid = Convert.ToInt32(spdn);
                    var kq = (from n in db.SanPhams
                              where n.ID == iid
                              select n).FirstOrDefault<SanPham>();
                    if (kq != null)
                    {
                        s += "<ol id='cart-sidebar' class='mini-products-list'>";
                        s += "         <li class='item clearfix'>";
                        s += "<a href='"+Url.Action("XemChiTietSanPham", "Home", new
                                        {
                                            id = kq.ID,
                                            loaisp = Nongsan.StringUils.UrlRewrite(kq.LoaiSanPham.Ten_Loai),
                                            tensp = Nongsan
                                                .StringUils.UrlRewrite(kq.Ten)
                                        })+"' title='"+kq.Ten+"' class='product-image'><img src='" + kq.HinhAnhs.FirstOrDefault().ImagePath + "' data-srcx2='" + kq.HinhAnhs.FirstOrDefault().ImagePath + "' width='50' height='50' alt='"+kq.Ten+"'><span></span></a>";
                        s += "<div class='product-details'>";
                        s += "<a onclick='javascript: xoasp(" + kq.ID + ");' title='Gỡ bỏ item này' onClick='return confirm(&#39;Bạn có chắc chắn muốn xóa sản phẩm này khỏi giỏ hàng?&#39;);' class='btn-remove'>Gỡ bỏ item này</a>";
                        s += "    <a href='" + Url.Action("XemChiTietSanPham", "Home", new
                        {
                            id = kq.ID,
                            loaisp = Nongsan.StringUils.UrlRewrite(kq.LoaiSanPham.Ten_Loai),
                            tensp = Nongsan
                                .StringUils.UrlRewrite(kq.Ten)
                        }) + "' title='Thay đổi sản phẩm' class='btn-edit'>Thay đổi sản phẩm</a>";
                        s += "       <p class='product-name'><a href='" + Url.Action("XemChiTietSanPham", "Home", new
                        {
                            id = kq.ID,
                            loaisp = Nongsan.StringUils.UrlRewrite(kq.LoaiSanPham.Ten_Loai),
                            tensp = Nongsan
                                .StringUils.UrlRewrite(kq.Ten)
                        }) + "'>" + kq.Ten + "</a></p>";
                        s += "<strong>" + soluong + "</strong>" + " x";


                        s += "     <span class='price'>" + kq.Gia + "đ</span> ";

                        tongtien = tongtien + (soluong * kq.Gia);


                        s += "</div>";
                        s += "</li>";
                        s += "         </ol>";
                    }
                }
                s += "<div class='subtotal-wrapper'>";
                s += "<div class='subtotal'>";
                s += "               <span class='label'>Tổng tiền:</span> <span class='price'>" + tongtien + " đ</span></div>";
                s += "</div>";
                s += "<div class='buttons clearfix'>";

                s += "<a href='" + @Url.Action("Thanhtoan", "Home") + "'><button type='button' title='Đặt mua' class='button btn-checkout')'><span><span>Thanh toán tiền</span></span></button></a>";
                s += "</div>";
                Response.Write(s);
            }
            else
            {
                string s = "";
                s += "<div class='details-border'></div>";
                s += "<p class='a-center'>Bạn không có sản phẩm nào trong giỏ hàng.</p>";
                Response.Write(s);
            }
            return null;
        }

        public ActionResult Xoasanphammoithemwithqty(string Id)
        {

            HttpCookie cookie = Request.Cookies["test"];
            if (cookie == null)
            {
                cookie = new HttpCookie("test");
                cookie["count"] = 0 + "";
                cookie.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(cookie);
            }

            // lay so luong cua san pham id
            int dem = Convert.ToInt32(cookie["count"]);
            int sl = 0;
            for (int j = 0; j < dem; j++)
            {
                if (cookie[j + ""] == Id)
                {
                    sl++;
                }
            }

            //tao ra list moi voi san pham id duoc bo di
            List<string> lstbd = new List<string>();
            for (int j = 0; j < dem; j++)
            {
                if (cookie[j + ""] != Id)
                {
                    lstbd.Add(cookie[j + ""]);
                }
            }

            cookie = new HttpCookie("test");
            cookie["count"] = 0 + "";
            cookie.Expires = DateTime.Now.AddDays(10);
            Response.Cookies.Add(cookie);

            for (int i = 0; i < lstbd.Count; i++)
            {
                cookie[i + ""] = lstbd[i];

            }
            cookie["count"] = lstbd.Count.ToString();
            Response.Cookies.Add(cookie);

            
            //int c = Convert.ToInt32(soluongmoi);
            //for (int i = 0; i < c; i++)
            //{
            //    int cc = Convert.ToInt32(cookie["count"]);

            //    cookie[cc + ""] = Id;

            //    cookie["count"] = (cc + 1).ToString();

            //    cookie.Expires = DateTime.Now.AddDays(10);
            //    Response.Cookies.Add(cookie);
            //}

            return null;
        }

        public ActionResult Getsanphammoithemwithqty(string Id,string soluongmoi)
        {

            HttpCookie cookie = Request.Cookies["test"];
            if (cookie == null)
            {
                cookie = new HttpCookie("test");
                cookie["count"] = 0 + "";
                cookie.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(cookie);
            }

            // lay so luong cua san pham id
            int dem = Convert.ToInt32(cookie["count"]);
            int sl = 0;
            for (int j = 0; j < dem; j++)
            {
                if (cookie[j + ""] == Id)
                {
                    sl++;
                }
            }

            //tao ra list moi voi san pham id duoc bo di
            List<string> lstbd = new List<string>();
            for (int j = 0; j < dem; j++)
            {
                if (cookie[j + ""] != Id)
                {
                    lstbd.Add(cookie[j + ""]);
                }
            }

            cookie = new HttpCookie("test");
            cookie["count"] = 0 + "";
            cookie.Expires = DateTime.Now.AddDays(10);
            Response.Cookies.Add(cookie);

            for (int i = 0; i < lstbd.Count; i++)
            {
                cookie[i + ""] = lstbd[i];

            }
            cookie["count"] = lstbd.Count.ToString();

            int c = Convert.ToInt32(soluongmoi);
            for (int i = 0; i < c; i++)
            {
                int cc = Convert.ToInt32(cookie["count"]);

                cookie[cc + ""] = Id;

                cookie["count"] = (cc + 1).ToString();

                cookie.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(cookie);
            }
           
            return null;
        }

        public ActionResult Getsanphammoithem(string Id)
        {

            HttpCookie cookie = Request.Cookies["test"];
            if (cookie == null)
            {
                cookie = new HttpCookie("test");
                cookie["count"] = 0 + "";
                cookie.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(cookie);
            }


            int dem = Convert.ToInt32(cookie["count"]);

            cookie[dem + ""] = Id;

            cookie["count"] = (dem + 1).ToString();

            cookie.Expires = DateTime.Now.AddDays(10);
            Response.Cookies.Add(cookie);

            if (cookie["count"] != "0")
            {

                List<string> lst = new List<string>();
                for (int j = 0; j < dem + 1; j++)
                {
                    lst.Add(cookie[j + ""]);
                }

                string s = "";
                int tongtien = 0;
                s += "<div class='details-border'></div><p class='block-subtitle text-recently'>Sản phẩm mới thêm</p>";

                List<string> lstspmdn = dsspmoithemduynhat(lst);
                foreach (string spdn in lstspmdn)
                {
                    int soluong = 0;

                    foreach (string ss in lst)
                    {
                        if (ss == spdn)
                        {
                            soluong++;
                        }


                    }
                    int iid = Convert.ToInt32(spdn);
                    var kq = (from n in db.SanPhams
                              where n.ID == iid
                              select n).FirstOrDefault<SanPham>();
                    if (kq != null)
                    {
                        s += "<ol id='cart-sidebar' class='mini-products-list'>";
                        s += "         <li class='item clearfix'>";
                        s += "<a href='" + Url.Action("XemChiTietSanPham", "Home", new
                        {
                            id = kq.ID,
                            loaisp = Nongsan.StringUils.UrlRewrite(kq.LoaiSanPham.Ten_Loai),
                            tensp = Nongsan
                                .StringUils.UrlRewrite(kq.Ten)
                        }) + "' title='"+kq.Ten+"' class='product-image'><img src='" + kq.HinhAnhs.FirstOrDefault().ImagePath + "' data-srcx2='" + kq.HinhAnhs.FirstOrDefault().ImagePath + "' width='50' height='50' alt='"+kq.Ten+"'><span></span></a>";
                        s += "<div class='product-details'>";
                        s += "<a onclick='javascript: xoasp(" + kq.ID + ");' title='Gỡ bỏ item này' onClick='return confirm(&#39;Bạn có chắc chắn muốn xóa sản phẩm này khỏi giỏ hàng?&#39;);' class='btn-remove'>Gỡ bỏ item này</a>";
                        s += "    <a href='" + Url.Action("XemChiTietSanPham", "Home", new
                        {
                            id = kq.ID,
                            loaisp = Nongsan.StringUils.UrlRewrite(kq.LoaiSanPham.Ten_Loai),
                            tensp = Nongsan
                                .StringUils.UrlRewrite(kq.Ten)
                        }) + "' title='Thay đổi sản phẩm' class='btn-edit'>Thay đổi sản phẩm</a>";
                        s += "       <p class='product-name'><a href='" + Url.Action("XemChiTietSanPham", "Home", new
                        {
                            id = kq.ID,
                            loaisp = Nongsan.StringUils.UrlRewrite(kq.LoaiSanPham.Ten_Loai),
                            tensp = Nongsan
                                .StringUils.UrlRewrite(kq.Ten)
                        }) + "'>" + kq.Ten + "</a></p>";
                        s += "<strong>" + soluong + "</strong>" + " x";


                        s += "     <span class='price'>" + kq.Gia + "đ</span> ";

                        tongtien = tongtien + (soluong * kq.Gia);


                        s += "</div>";
                        s += "</li>";
                        s += "         </ol>";
                    }
                }
                s += "<div class='subtotal-wrapper'>";
                s += "<div class='subtotal'>";
                s += "               <span class='label'>Tổng tiền:</span> <span class='price'>" + tongtien + " đ</span></div>";
                s += "</div>";
                s += "<div class='buttons clearfix'>";

                s += "<a href='" + @Url.Action("Thanhtoan", "Home") + "'><button type='button' title='Đặt mua' class='button btn-checkout')'><span><span>Thanh toán tiền</span></span></button></a>";
                s += "</div>";
                Response.Write(s);
            }
            else
            {
                string s = "";
                s += "<div class='details-border'></div>";
                s += "<p class='a-center'>Bạn không có sản phẩm nào trong giỏ hàng.</p>";
                Response.Write(s);
            }
            return null;
        }

        List<String> dsspmoithemduynhat(List<string> lst)
        {
            List<string> lstspmdn = new List<string>();
            foreach (string s in lst)
            {
                if (!lstspmdn.Contains(s))
                {
                    lstspmdn.Add(s);
                }
            }
            return lstspmdn;
        }

        public JsonResult GetJsonsanphammoi(string location)
        {
            List<string> wd = new List<string>();
            wd.Add("1");
            wd.Add("2");
            wd.Add("3");
            wd.Add("4");
            return Json(wd, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Xemgiohang()
        {
            HttpCookie cookie = Request.Cookies["test"];
            if (cookie == null)
            {
                cookie = new HttpCookie("test");
                cookie["count"] = 0 + "";
                cookie.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(cookie);
            }

            int dem = Convert.ToInt32(cookie["count"]);

            List<string> lst = new List<string>();
            for (int j = 0; j < dem + 1; j++)
            {
                lst.Add(cookie[j + ""]);
            }

            List<string> lstspdn = dsspmoithemduynhat(lst);
            List<SanPham> lstsp = new List<SanPham>();
            foreach (SanPham sp in db.SanPhams)
            {
                foreach (string s in lstspdn)
                {
                    if (sp.ID == Convert.ToInt32(s))
                    {
                        lstsp.Add(sp);
                    }
                }
            }

            List<int> sl = new List<int>();
            foreach (SanPham spdn in lstsp)
            {
                int soluong = 0;

                foreach (string ss in lst)
                {
                    if (ss == spdn.ID.ToString())
                    {
                        soluong++;
                    }
                }
                sl.Add(soluong);
            }
            ViewBag.soluong = sl;
            ViewBag.dssanphamdn = lstsp;
            
            return View();
        }

        public ActionResult Thanhtoan()
        {
            HttpCookie cookie = Request.Cookies["test"];
            if (cookie == null)
            {
                cookie = new HttpCookie("test");
                cookie["count"] = 0 + "";
                cookie.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(cookie);
            }

            int dem = Convert.ToInt32(cookie["count"]);

            List<string> lst = new List<string>();
            for (int j = 0; j < dem + 1; j++)
            {
                lst.Add(cookie[j + ""]);
            }

            List<string> lstspdn = dsspmoithemduynhat(lst);
            List<SanPham> lstsp = new List<SanPham>();
            foreach (SanPham sp in db.SanPhams)
            {
                foreach (string s in lstspdn)
                {
                    if (sp.ID == Convert.ToInt32(s))
                    {
                        lstsp.Add(sp);
                    }
                }
            }

            List<int> sl = new List<int>();
            foreach (SanPham spdn in lstsp)
            {
                int soluong = 0;

                foreach (string ss in lst)
                {
                    if (ss == spdn.ID.ToString())
                    {
                        soluong++;
                    }
                }
                sl.Add(soluong);
            }
            ViewBag.soluong = sl;
            ViewBag.dssanphamdn = lstsp;
            return View();
        }

        [HttpPost]
        public ActionResult Thanhtoan(HoaDon hoadon)
        {
            HttpCookie cookie = Request.Cookies["test"];
            if (cookie == null)
            {
                cookie = new HttpCookie("test");
                cookie["count"] = 0 + "";
                cookie.Expires = DateTime.Now.AddDays(10);
                Response.Cookies.Add(cookie);
            }

            int dem = Convert.ToInt32(cookie["count"]);

            List<string> lst = new List<string>();
            for (int j = 0; j < dem + 1; j++)
            {
                lst.Add(cookie[j + ""]);
            }

            List<string> lstspdn = dsspmoithemduynhat(lst);
            List<SanPham> lstsp = new List<SanPham>();
            foreach (SanPham sp in db.SanPhams)
            {
                foreach (string s in lstspdn)
                {
                    if (sp.ID == Convert.ToInt32(s))
                    {
                        lstsp.Add(sp);
                    }
                }
            }

            List<int> sl = new List<int>();
            foreach (SanPham spdn in lstsp)
            {
                int soluong = 0;

                foreach (string ss in lst)
                {
                    if (ss == spdn.ID.ToString())
                    {
                        soluong++;
                    }
                }
                sl.Add(soluong);
            }
            ViewBag.soluong = sl;
            ViewBag.dssanphamdn = lstsp;
            //hoadon.Ngay_thang = DateTime.Now;
            //hoadon.ID_Nguoidung = 1;
            //hoadon.Phi_ship = 10000;
            //hoadon.Tong_tien = 0;
            //hoadon.Trang_thai = false;
            //hoadon.SDT_nhan = 13123123123123;
            //hoadon.Dia_chi_nhan = "asdasd";
            //hoadon.Ho_ten_nhan = "xcvcxv";
            //hoadon.Ghi_chu = "nm,mn,";
            //hoadon.Email_nhan = "asdas@asda.com";
            db.HoaDons.Add(hoadon);
            if (ModelState.IsValid)
            {
                //hoadon.Ngay_thang = DateTime.Now;
                //hoadon.ID_Nguoidung = 1;
                //hoadon.Phi_ship = 10000;
                //hoadon.Tong_tien = 0;
                //hoadon.Trang_thai = false;
                db.HoaDons.Add(hoadon);
                db.SaveChanges();
                for (int i = 0; i < lstsp.Count; i++)
                {
                    ChiTietHoaDon cthd = new ChiTietHoaDon();
                    cthd.ID_Hoadon = hoadon.ID;
                    cthd.ID_Sanpham = lstsp[i].ID;
                    cthd.So_luong = sl[i];
                    cthd.Thanh_tien = lstsp[i].Gia * sl[i];

                    db.ChiTietHoaDons.Add(cthd);
                    db.SaveChanges();
                }
                return RedirectToAction("Index");
                
                
            }
           

            return View(hoadon);
        }

        public ActionResult Taotaikhoan()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Taotaikhoan(NguoiDung nguoidung)
        {
            if (ModelState.IsValid)
            {

                db.NguoiDungs.Add(nguoidung);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(nguoidung);
        }
    }
}
